<script>
import {
  apiAddAndEditHighFormWorkDetectInfo,
  apiAddHighFormWorkDetectList,
  apiDeleteHighFormWorkDetectListItem,
} from '@/apis/highFormWork.api';
import infoAndFile from '@/views/bigDevice/components/InfoAndFile.vue';

export default {
  name: '',
  components: { infoAndFile },
  data() {
    return {
      infoModule: {
        title: '检测数据',
        // 信息结构
        detailColumns: [
          [
            {
              label: '搭设高度(m)',
              prop: 'high',
            },
            {
              label: '搭设跨度(m)',
              prop: 'weigh',
            },
            {
              label: '使用部位',
              prop: 'position',
            },
          ],
          [
            {
              label: '施工总荷载(kN/㎡)',
              prop: 'sumLoad',
            },
            {
              label: '集中线荷载(kN/㎡)',
              prop: 'busLoad',
            },
          ],
          [
            {
              label: '关联设备编号',
              prop: 'deviceSn',
            },
            {
              label: '关联设备名称',
              prop: 'deviceName',
            },
          ],
        ],
      },
      infoData: {},
      formColumns: [
        {
          label: '搭设高度',
          prop: 'high',
          append: '米',
          contentType: 'number',
          precision: 2,
          max: 20,
          rules: [
            {
              required: true,
              message: '请输入搭设高度',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '施工总荷载',
          prop: 'sumLoad',
          append: 'kN/㎡',
          contentType: 'number',
          precision: 2,
          max: 20,
          rules: [
            {
              required: true,
              message: '请输入施工总荷载',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '关联设备编号',
          prop: 'deviceSn',
          rules: [
            {
              required: true,
              message: '请输入关联设备编号',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '搭设跨度',
          prop: 'weigh',
          append: '米',
          contentType: 'number',
          precision: 2,
          max: 20,
          rules: [
            {
              required: true,
              message: '请输入搭设跨度',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '集中线荷载',
          prop: 'busLoad',
          append: 'kN/㎡',
          contentType: 'number',
          precision: 2,
          max: 20,
          rules: [
            {
              required: true,
              message: '请输入集中线荷载',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '关联设备名称',
          prop: 'deviceName',
          rules: [
            {
              required: true,
              message: '请输入关联设备名称',
              trigger: 'blur',
            },
          ],
        },
        {
          label: '使用部位',
          prop: 'position',
          max: 200,
          rules: [
            {
              required: true,
              message: '请输入使用部位',
              trigger: 'blur',
            },
          ],
        },
      ],
      formData: {},
      searchDate: [],
      tableColumns: [
        {
          type: 'serial',
          label: '序号',
          width: 60,
          align: 'center',
        },
        {
          prop: 'checkName',
          label: '检测点名称',
        },
        {
          prop: 'checkDate',
          label: '检测时间',
        },
        {
          prop: 'polingAxialForce',
          label: '立杆轴力(N)',
        },
        {
          prop: 'horizontalDisplacement',
          label: '水平位移(mm)',
        },
        {
          prop: 'verticalAngle',
          label: '立杆倾角(°)',
        },
        {
          prop: 'isAlarm',
          label: '是否告警',
        },
        {
          prop: 'description',
          label: '说明',
        },
        {
          prop: 'options',
          label: '操作',
        },
      ],
      tableData: [
        {
          id: 1,
          checkName: '监测点名称',
          checkDate: '检测时间',
          polingAxialForce: '立杆轴力(N)',
          horizontalDisplacement: '水平位移(mm)',
          verticalAngle: '立杆倾角(°)',
          isAlarm: '是否警告',
          description: '说明',
        },
      ],
      dynamicRowData: {
        rowData: [],
      },
      tableFormRules: {
        checkName: [
          {
            required: true,
            message: '请输入检测点名称',
            trigger: 'blur',
          },
        ],
        checkDate: [
          {
            required: true,
            message: '请选择检测时间',
            trigger: 'blur',
          },
        ],
        polingAxialForce: [
          {
            required: true,
            message: '请输入立杆轴力',
            trigger: 'blur',
          },
        ],
        horizontalDisplacement: [
          {
            required: true,
            message: '请输入水平位移',
            trigger: 'blur',
          },
        ],
        verticalAngle: [
          {
            required: true,
            message: '请输入立杆倾角',
            trigger: 'blur',
          },
        ],
        isAlarm: [
          {
            required: true,
            message: '请选择是否告警',
            trigger: 'change',
          },
        ],
        description: [
          {
            required: true,
            message: '请输入说明',
            trigger: 'blur',
          },
        ],
      },
      showDialog: false,
      dialogSearchData: {},
      dialogTableColumns: [
        {
          prop: 'check',
          width: 50,
          align: 'center',
        },
        {
          type: 'serial',
          label: '序号',
          width: 60,
          align: 'center',
        },
        {
          prop: 'deviceName',
          label: '设备名称',
        },
        {
          prop: 'deviceSn',
          label: '设备编号',
        },
        {
          prop: 'projectName',
          label: '项目名称',
        },
        {
          prop: 'projectCode',
          label: '住建项目编号',
        },
      ],
      dialogTableData: [
        {
          id: 1,
          deviceName: '设备名称1',
          deviceSn: '设备编号1',
          projectName: '项目名称1',
          projectCode: '住建项目编号1',
        },
        {
          id: 2,
          deviceName: '设备名称2',
          deviceSn: '设备编号2',
          projectName: '项目名称2',
          projectCode: '住建项目编号2',
        },
        {
          id: 3,
          deviceName: '设备名称3',
          deviceSn: '设备编号3',
          projectName: '项目名称3',
          projectCode: '住建项目编号3',
        },
      ],
      dialogTableActive: {},
      dialogTableActiveId: '',
      dialogPaginationData: {
        total: 0,
        pageSize: 20,
        pageNumber: 1,
      },
      timer: null,
      loading: false,
    };
  },
  computed: {
    dialogFormColumns() {
      return [{ prop: 'deviceName', label: '设备名称', component: 'el-input' }];
    },
  },
  watch: {
    searchDate() {
      this.getList();
    },
  },
  created() {
    this.getDetail();
    this.getList();
  },
  destroyed() {
    clearTimeout(this.timer);
  },
  methods: {
    async getDetail() {
      // const res = await apiGetHighFormWorkDetectInfo(this.$route.query.rpid);
      // this.formData = res.response;
    },
    async getList() {
      // const res = await apiGetHighFormWorkDetectList({
      //   riskBigProjectId: this.$route.query.rpid,
      //   startDate: this.searchDate[0],
      //   endDate: this.searchDate[1],
      // });
      // this.tableData = res.response.data.map((item) => {
      //   item.isAlarm = item.isAlarm ? '是' : '否';
      //   return item;
      // });
      this.calculateTableHeight();
    },
    addTableRow() {
      this.$refs.tableForm.validate((valid) => {
        if (valid) {
          this.tableData.push({
            rowType: 'editRow',
            index: this.dynamicRowData.rowData.length,
          });
          this.dynamicRowData.rowData.push({});
          this.calculateTableHeight();
        }
      });
    },
    async remove(row) {
      if (row.rowType === 'editRow') {
        this.tableData = this.tableData.filter((item) => item.index !== row.index);
        this.dynamicRowData.rowData[row.index].isDelete = true;
        this.$refs.tableForm.clearValidate();
      } else {
        const res = await apiDeleteHighFormWorkDetectListItem(row.id);
        if (res.status === 0) {
          this.$message.success('删除成功');
          this.tableData = this.tableData.filter((item) => item.id !== row.id);
        }
      }
      this.calculateTableHeight();
    },
    submit(e) {
      this.$refs.tableForm.validate(async (valid) => {
        if (valid) {
          const res = await apiAddAndEditHighFormWorkDetectInfo(e);
          console.log(res);
          const tableFormList = this.dynamicRowData.rowData.filter((item) => !item.isDelete);
          if (tableFormList.length) {
            const res = await apiAddHighFormWorkDetectList(tableFormList);
            console.log(res);
          }
          this.$router.back();
        }
      });
    },
    getFocus(prop) {
      if (prop === 'deviceSn' || prop === 'deviceName') {
        this.showDialog = true;
        this.findActive();
      }
    },
    searchDevice() {},
    reset() {
      this.dialogSearchData = {};
    },
    dialogTableRowClick(row) {
      this.dialogTableActiveId = row.id;
      this.dialogTableActive = row;
    },
    selectionChange(val, row) {
      if (val) {
        this.dialogTableActive = row;
      }
    },
    pageChange(page) {
      console.log(page);
    },
    confirm() {
      this.showDialog = false;
      this.$set(this.formData, 'deviceSn', this.dialogTableActive.deviceSn);
      this.$set(this.formData, 'deviceName', this.dialogTableActive.deviceName);
      this.$refs.infoAndFile.$children[0].clearValid();
    },
    cancel() {
      this.showDialog = false;
      this.dialogTableActiveId = '';
      this.dialogTableActive = null;
    },
    findActive() {
      this.dialogTableActive = this.dialogTableData.find(
        (item) => item.deviceSn === this.formData.deviceSn || item.deviceName === this.formData.deviceName
      );
      this.dialogTableActiveId = this.dialogTableActive?.id ?? '';
    },
    calculateTableHeight() {
      this.timer = setTimeout(() => {
        document.querySelector('.el-table').style.height = (70 * this.tableData.length || 100) + 40 + 'px';
      }, 0);
    },
  },
};
</script>

<template>
  <div class="detect">
    <div class="dataForm">
      <info-and-file
        ref="infoAndFile"
        :info-module="infoModule"
        :info-data="infoData"
        :form-columns="formColumns"
        :form-data="formData"
        :form-label-width="150"
        :has-file-module="false"
        :has-edit="true"
        @submit="submit"
        @getFocus="getFocus"
      ></info-and-file>
    </div>

    <div class="list">
      <div class="title">
        <div></div>
        <div>检测列表</div>
      </div>

      <div class="option">
        <el-form>
          <el-form-item label="检测时间">
            <el-date-picker
              v-model="searchDate"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
            <div class="space">
              <el-button @click="addTableRow">
                <i class="icon el-icon-circle-plus-outline"></i>
                添加
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <el-form ref="tableForm" :model="dynamicRowData" :rules="tableFormRules">
        <el-table-common :columns="tableColumns" :data="tableData" :height="100" :pagination="false">
          <template #checkName="scope">
            <el-form-item
              v-if="scope.row.rowType === 'editRow'"
              :prop="'rowData.' + scope.row.index + '.checkName'"
              :rules="tableFormRules.checkName"
            >
              <el-input
                v-model="dynamicRowData.rowData[scope.row.index].checkName"
                maxlength="100"
                placeholder="请输入监测点名称"
              ></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.checkName }}</span>
          </template>
          <template #checkDate="scope">
            <el-form-item
              v-if="scope.row.rowType === 'editRow'"
              :prop="'rowData.' + scope.row.index + '.checkDate'"
              :rules="tableFormRules.checkDate"
            >
              <el-date-picker
                v-model="dynamicRowData.rowData[scope.row.index].checkDate"
                value-format="yyyy-MM-dd"
                placeholder="请选择检测时间"
              ></el-date-picker>
            </el-form-item>
            <span v-else>{{ scope.row.checkDate }}</span>
          </template>
          <template #polingAxialForce="scope">
            <el-form-item
              v-if="scope.row.rowType === 'editRow'"
              :prop="'rowData.' + scope.row.index + '.polingAxialForce'"
              :rules="tableFormRules.polingAxialForce"
            >
              <el-input-number
                :precision="2"
                controls-position="right"
                placeholder="请输入立杆轴力"
                v-model="dynamicRowData.rowData[scope.row.index].polingAxialForce"
              ></el-input-number>
            </el-form-item>
            <span v-else>{{ scope.row.polingAxialForce }}</span>
          </template>
          <template #horizontalDisplacement="scope">
            <el-form-item
              v-if="scope.row.rowType === 'editRow'"
              :prop="'rowData.' + scope.row.index + '.horizontalDisplacement'"
              :rules="tableFormRules.horizontalDisplacement"
            >
              <el-input-number
                :precision="2"
                controls-position="right"
                placeholder="请输入水平位移"
                v-model="dynamicRowData.rowData[scope.row.index].horizontalDisplacement"
              ></el-input-number>
            </el-form-item>
            <span v-else>{{ scope.row.horizontalDisplacement }}</span>
          </template>
          <template #verticalAngle="scope">
            <el-form-item
              v-if="scope.row.rowType === 'editRow'"
              :prop="'rowData.' + scope.row.index + '.verticalAngle'"
              :rules="tableFormRules.verticalAngle"
            >
              <el-input-number
                :precision="2"
                controls-position="right"
                placeholder="请输入立杆倾角"
                v-model="dynamicRowData.rowData[scope.row.index].verticalAngle"
              ></el-input-number>
            </el-form-item>
            <span v-else>{{ scope.row.verticalAngle }}</span>
          </template>
          <template #isAlarm="scope">
            <el-form-item
              v-if="scope.row.rowType === 'editRow'"
              :prop="'rowData.' + scope.row.index + '.isAlarm'"
              :rules="tableFormRules.isAlarm"
            >
              <el-select v-model="dynamicRowData.rowData[scope.row.index].isAlarm" placeholder="请选择是否告警">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
            <span v-else>{{ scope.row.isAlarm }}</span>
          </template>
          <template #description="scope">
            <el-form-item
              v-if="scope.row.rowType === 'editRow'"
              :prop="'rowData.' + scope.row.index + '.description'"
              :rules="tableFormRules.description"
            >
              <el-input
                v-model="dynamicRowData.rowData[scope.row.index].description"
                maxlength="100"
                placeholder="请输入说明"
              ></el-input>
            </el-form-item>
            <span v-else>{{ scope.row.description }}</span>
          </template>
          <template #options="scope">
            <el-popconfirm
              title="删除后无法恢复，确定删除吗？"
              icon-color="red"
              icon="el-icon-info"
              @confirm="remove(scope.row)"
            >
              <el-button slot="reference" type="text">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-common>
      </el-form>
    </div>

    <el-dialog title="选择关联设备" :visible.sync="showDialog" width="80%" top="5vh" @close="showDialog = false">
      <form-common
        :columns="dialogFormColumns"
        :data="dialogSearchData"
        inline
        label-width="73px"
        @search="searchDevice"
        @reset="reset"
      ></form-common>
      <el-table-common
        ref="dialogTable"
        v-loading="loading"
        :data="dialogTableData"
        :columns="dialogTableColumns"
        :pagination-data="dialogPaginationData"
        :height="600"
        @pageChange="pageChange"
        @row-click="dialogTableRowClick"
      >
        <template #check="scope">
          <el-radio v-model="dialogTableActiveId" :label="scope.row.id" @change="selectionChange($event, scope.row)">
            <span></span>
          </el-radio>
        </template>
      </el-table-common>
      <div class="button-group" slot="footer">
        <el-button type="primary" @click="confirm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.title {
  font-size: 16px;
  color: #1a1a1a;
  display: flex;
  align-items: center;
  margin-bottom: 18px;

  div:first-of-type {
    width: 4px;
    height: 16px;
    background: #4091ff;
    margin-right: 8px;
  }
}

.detect {
  .dataForm {
    border-bottom: 1px solid #eeeeee;
    padding-bottom: 14px;
    margin-bottom: 32px;

    ::v-deep .el-form {
      .el-form-item:last-of-type {
        width: 100%;
        margin-right: 0;
      }
    }
  }

  .list {
    .option {
      ::v-deep .el-form-item__content {
        display: flex;

        .space {
          flex: 1;
          display: flex;
          justify-content: flex-end;

          .el-button {
            color: #4091ff;
            border-color: #4091ff;
          }
        }
      }
    }

    ::v-deep .el-table {
      td {
        height: 70px;
        padding: 0;

        .el-form-item {
          margin-top: 18px;

          .el-date-editor {
            width: auto;
            max-width: 180px;
          }

          .el-input-number {
            width: auto;
            max-width: 180px;

            span {
              display: none;
            }

            input {
              text-align: left;
              padding-right: 15px;
            }
          }
        }
      }
    }
  }

  ::v-deep .el-dialog__wrapper {
    .el-dialog__header {
      padding: 16px 24px;
      border-bottom: 1px solid #eeeeee;

      .el-dialog__title {
        font-size: 18px;
        color: #1a1a1a;
      }
    }

    .el-dialog__body {
      padding: 16px 24px;

      thead th:first-of-type .cell {
        display: none;
      }

      .el-radio__label {
        padding: 0;
      }
    }

    .el-dialog__footer {
      padding: 16px 24px;
      border-top: 1px solid #eeeeee;

      .button-group {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}
</style>
